
import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client'
import { Menu } from 'antd'
import type { MenuProps } from 'antd';

type MenuItem = Required<MenuProps>['items'][number];

type ContextMenuProps = {
    width?: number;
    x: number;
    y: number;
    menuItems: MenuItem[];
    onHide: () => void;
    onClick: (e: any) => void
}

function ContextMenu(props: ContextMenuProps) {

    useEffect(() => {
        const onHide: any = () => {
            props.onHide()
        }
        document.body.addEventListener('click', onHide, false)
        return () => {
            document.body.removeEventListener('click', onHide, false)
        }
    }, [])


    return <div
        style={{
            position: 'fixed',
            left: props.x,
            top: props.y
        }}
        className='_context_menu__'
    >
        <Menu
            onClick={props.onClick}
            style={{ width: props.width + 'px' }}
            mode="vertical"
            selectable={false}
            items={props.menuItems}
        />
    </div>
}

export function showContextMenu(props: ContextMenuProps) {

    hideContextMenu()

    const id = '_context_menus__'
    let $el = document.getElementById(id)
    if (!$el) {
        $el = document.createElement('div');
        $el.id = id;
        document.body.appendChild($el)
    }

    const root = createRoot($el)

    root.render(<ContextMenu
        {
        ...props
        }
        onHide={() => {
            root.unmount();
        }}
    />)

}

export function hideContextMenu(): void {
    const $el = document.getElementById('_context_menus__')
    if ($el) {
        $el.remove()
    }
}
